package com.huangmingfu;

import java.util.Arrays;

/**
 * @Author: 黄名富
 * @Description: 策略模式
 */
public class StrategyPattern {

    public static void main(String[] args) {
        SortAlgorithm[] sortAlgorithms = {new BubbleSortAlgorithm(),new SelectionSortAlgorithm()};
        Integer[][] array = {{34,23,2,4,6,44,11,53,221,123},{3,66,27,212,45,565,11,44,33,12,465,55,22,14,56}};
        for (SortAlgorithm sortAlgorithm : sortAlgorithms) {
            for (Integer[] arr : array) {
                sortAlgorithm.sort(arr);
            }
            System.out.println();
        }
    }

    private static abstract class SortAlgorithm {
        public void sort(Integer[] array) { // 升序
            if (array != null && array.length > 1) {
                array = Arrays.copyOf(array,array.length);
                opera(array);
                System.out.println(Arrays.asList(array));
            }
        }

        protected abstract void opera(Integer[] array);
    }

    /**
     * 冒泡排序
     */
    private static class BubbleSortAlgorithm extends SortAlgorithm{
        @Override
        protected void opera(Integer[] array) {
            for (int i = 0; i < array.length; i++) {
                for (int j = i + 1; j < array.length; j++) {
                    if (array[i] > array[j]) {
                        int temp = array[j];
                        array[j] = array[i];
                        array[i] = temp;
                    }
                }
            }
        }
    }

    /**
     * 选择排序
     */
    private static class SelectionSortAlgorithm extends SortAlgorithm {
        @Override
        protected void opera(Integer[] array) {
            for (int i = 0; i < array.length; i++) {
                int minPos = i;
                for (int j = i+1; j <array.length; j++) {
                    if (array[minPos] > array[j]) {
                        minPos = j;
                    }
                }
                int temp = array[i];
                array[i] = array[minPos];
                array[minPos] = temp;
            }
        }
    }

}
